package com.term.util.annotation.type;

import com.term.domain.common.ConditionSet;
import com.term.util.annotation.FuzzyPattern;
import com.term.util.converter.ClassUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by chenGang on 2017/2/10.
 */
public class FuzzyQueryUtils {

    /**
     * 就是单纯的类型转换，没有涉及到比较复杂的情况
     * @param obj
     * @return
     */
    public static Map<String, Object> convertQueryToMap(Object obj) {
        HashMap map = new HashMap();
        Class targetClass = obj.getClass();
        Field[] fields = targetClass.getDeclaredFields();
        for(int i = 0; i < fields.length; ++i) {
            Field field = fields[i];
            String name = field.getName();
            Object value = ClassUtils.getValue(obj, name);
            if(value != null && !"".equals(value)) {
                map.put(name, value);
            }
        }
        return map;
    }


    /**
     * 该方法主要是用于模糊查询
     * @param object
     * @return
     */
    public static ConditionSet convertQueryToConditionSet(Object object) {
        ConditionSet conditionSet = new ConditionSet();
        Class targetClass = object.getClass();
        Field[] fields = targetClass.getDeclaredFields();
        for(int i = 0; i < fields.length; ++i) {
            Field field = fields[i];
            String name = field.getName();
            Object value = ClassUtils.getValue(object, name);
            if(value != null && !"".equals(value)) {
                if(field.isAnnotationPresent(FuzzyPattern.class)) {
                    FuzzyPattern fuzzyPattern = (FuzzyPattern)field.getAnnotation(FuzzyPattern.class);
                    name = "".equals(fuzzyPattern.name())?name:fuzzyPattern.name();
                    value = convertValue(value, fuzzyPattern);
                    conditionSet.addCondition(name, value, fuzzyPattern.matchType());
                } else {
                    conditionSet.addCondition(name, value);
                }
            }
        }
        return conditionSet;
    }

    private static Object convertValue(Object value, FuzzyPattern fuzzyPattern) {
        Class targetClass = fuzzyPattern.targetClass();
        if(targetClass.equals(Long[].class)) {
            Long[] longs = new Long[]{Long.valueOf(String.valueOf(value))};
            return longs;
        } else if(targetClass.equals(Object.class)) {
            return value;
        } else {
            if(targetClass.equals(Boolean.class)) {
                value = value.equals("true") ? Boolean.TRUE : Boolean.FALSE;
            }
            return value;
        }
    }
}